package org.singledog.form.builder.view;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.Getter;
import org.singledog.form.builder.MagicConstants;
import org.singledog.form.builder.dataset.DataSetRegistry;
import org.singledog.form.builder.dataset.DataSetType;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * @author adam
 * @date 2019/6/2
 */
public abstract class AbstractView  implements View {

	@Getter
	protected final String viewCode;
	@Getter
	protected final JSONObject schema;

	public AbstractView(String viewCode, JSONObject schema) {
		this.viewCode = viewCode;
		this.schema = schema;
	}

	protected Map<String, Object> invokeDataSets(JSONObject schema) {
		Assert.notNull(schema, "schema can not be null !");

		JSONObject datasets = schema.getJSONObject(MagicConstants.DATASETS);
		if (CollectionUtils.isEmpty(datasets)) {
			return Collections.emptyMap();
		}

		Map<String, Object> ret = new HashMap<>();
		for (String key : datasets.keySet()) {
			JSONObject dataset = datasets.getJSONObject(key);
			ret.put(key, invokeDataSet(key, dataset));
		}

		return ret;
	}

	protected Object invokeDataSet(String datasetCode, JSONObject dataset) {
		Map<String, Object> params = new HashMap<>();
		JSONArray array = dataset.getJSONArray(MagicConstants.PARAMS);
		params.put(MagicConstants.LOCAL_DATASET_PARAM, array);
		for (int i = 0; i < array.size(); i++) {
			Object obj = array.get(i);
			if (obj instanceof JSONObject) {
				params.putAll((JSONObject) obj);
			}
		}

		return DataSetRegistry.queryDataSet(DataSetType.valueOf(dataset.getString(MagicConstants.TYPE))).queryData(datasetCode, params);
	}
}
